package de.gameduell.net.src.communication {
	import de.gameduell.framework.application.Settings;
	import de.gameduell.framework.debug.Debug;
	import de.gameduell.framework.util.FlashVars;
	import de.gameduell.net.src.protocol.IProtocol;
	import de.gameduell.net.src.protocol.ProtocolFactory;
	
	import flash.display.MovieClip;
	import flash.events.Event;
	import flash.events.StatusEvent;
	import flash.net.LocalConnection;	

	/**
	 * @author GD
	 */
	public class BaseCommunication extends MovieClip {
		private var localConnection:LocalConnection;
		
		protected var _version:String;	
		protected var messageQueue:MessageQueue;
		protected var protocolFactory:ProtocolFactory;
		protected var settings:Settings;
		protected var serviceType:String;
		protected var slotId:String;
		protected var ticket:String;
		protected var protocol:IProtocol;

		public function BaseCommunication(aVersion:String){
			super();
			_version        = aVersion;
			messageQueue    = new MessageQueue();
			protocolFactory = new ProtocolFactory();
			
			localConnection = new LocalConnection();
			localConnection.client = this;
			localConnection.allowDomain("*");
			localConnection.addEventListener(StatusEvent.STATUS, onStatusEvent);
		}
		
		public function init(aSettings:Settings,aTicket:String):void{	
			settings 	 = aSettings;
			serviceType  = settings.gameType + settings.gameVersion;
			slotId 		 = FlashVars.getKeyValue(FlashVars.GAME_ID);
			ticket 		 = aTicket;
	
			protocol 	 = protocolFactory.createProtocol(settings.protocol);
			protocol.init(serviceType, slotId, ticket);
		}
		
		public function localSend(aMethod:String, aMessage:String, aChannel:String = "local_data"):void {
			aChannel = FlashVars.getKeyValue("lcname") == FlashVars.NO_VALUE ? aChannel : FlashVars.getKeyValue("lcname");
			try{
				localConnection.send(aChannel, aMethod, aMessage);
			}catch(e:Error){
				Debug.trace("Standalone::localSend: "  +e.getStackTrace(), Debug.WARNING);
			}
		}
		
		public function getMessageQueue():MessageQueue {
			return messageQueue;
		}
		
		/**
		 * returns the type of the communication object
		 * can be: "Standalone" or "Communication"
		 */
		public function get version():String {
			return _version;
		}
		
		private function onStatusEvent(event:Event):void {}
	}
}
